package com.woniuxy.service.impl;

import com.woniuxy.dao.MenuDao;
import com.woniuxy.dao.RoleMenuDao;
import com.woniuxy.entity.Menu;
import com.woniuxy.service.MenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    @Resource
    MenuDao menuDao;
    @Resource
    RoleMenuDao roleMenuDao;
    @Override
    public List<Menu> selectMenus() {
        return menuDao.selectForChildren();
    }

    @Override
    public List<Menu> selectAll() {
        return menuDao.selectAll();
    }

    @Override
    public String insertOne(Menu rbacMenu) {
        int row = this.menuDao.insertOne(rbacMenu);
        String result = "新增一条权限信息失败";
        if (row == 1){
            result = "新增一条权限信息成功";
        }
        return result;
    }

    @Override
    public Menu selectOne(int id) {
        return menuDao.selectOne(id);
    }

    @Override
    public String deleteOne(int id) {
        int row = this.menuDao.deleteOne(id);
        String result = "删除一条权限信息失败";
        if (row == 1){
            result = "删除一条权限信息成功";
        }
        return result;
    }

    @Override
    public String updateOne(Menu rbacMenu) {
        int row = this.menuDao.updateOne(rbacMenu);
        String result = "修改一条权限信息失败";
        if (row == 1){
            result = "修改一条权限信息成功";
        }
        return result;
    }

    @Override
    public List<Menu> findLeftMenu(int id) {
        //查询出所有菜单数据
        List<Menu> allMenu = menuDao.selectForChildren();
        //查询当前角色所有的菜单id
        List<Integer> roleMenus = roleMenuDao.selectMenusById(id);
        //return值
        List<Menu> myMenu = new ArrayList<>();
        //迭代 第一级菜单 第二级菜单
        for (Menu first:
             allMenu) {
            //每一级菜单创建一个实体类
            Menu rbacMenu = first;
            //清空新实体类一级菜单下的所有菜单
            Iterator<Menu> iterator = first.getChildren().iterator();
            while (iterator.hasNext()){
                //循环判断是否包含菜单id
                if (!roleMenus.contains(iterator.next().getId())){
                    iterator.remove();
                }
            }
            //每次放入1级菜单
            myMenu.add(rbacMenu);
        }

        return myMenu;
    }
}
